package com.neusoft.yiyang.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.UUID;

/**
 * 核心功能：透传请求头（如 Authorization、X-Trace-Id）
 */
public class FeignAuthInterceptor implements RequestInterceptor {

    private static final String HEADER_AUTH = "Authorization";
    private static final String HEADER_TRACE_ID = "X-Trace-Id";

    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            // 透传 Authorization（用于跨服务鉴权）
            String authHeader = request.getHeader(HEADER_AUTH);
            if (authHeader != null) {
                template.header(HEADER_AUTH, authHeader);
            }
            // 透传或生成 Trace-ID（用于链路追踪）
            String traceId = request.getHeader(HEADER_TRACE_ID);
            template.header(HEADER_TRACE_ID, traceId != null ? traceId : generateTraceId());
        }
    }

    private HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }

    private String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
